<template>
  <view class="publish-container">
    <view class="content-card">
      <!-- 内容输入区 -->
      <textarea
        class="content-input"
        v-model="formData.content"
        placeholder="分享你的新鲜事..."
        :maxlength="1000"
        auto-height
      />

      <!-- 分隔线 -->
      <view class="divider"></view>

            <!-- 底部区域 -->
      <view class="bottom-section">
        <!-- 已上传的图片 -->
        <view class="image-list" v-if="imageList.length > 0">
          <view 
            class="image-item" 
            v-for="(image, index) in imageList" 
            :key="index"
          >
            <image 
              class="uploaded-image" 
              :src="image" 
              mode="aspectFill"
            />
            <view class="delete-btn" @click="deleteImage(index)">×</view>
          </view>
        </view>
        
        <!-- 图片上传按钮 -->
        <view class="image-upload" @click="chooseImage" v-if="imageList.length < 9">
          <view class="upload-box">
            <text class="plus-icon">+</text>
          </view>
        </view>
        
        <!-- 图片计数 -->
        <view class="image-counter">
          {{ imageList.length }}/9
        </view>
      </view>
    </view>

        <!-- 发布按钮 -->
    <view class="publish-btn-container">
      <ZButton
        type="secondary"
        :disabled="submitting || !formData.content.trim()"
        @click="submitPost"
      >
        {{ submitting ? '发布中...' : '发送' }}
      </ZButton>
    </view>
  </view>
</template>

<script>
import ZButton from '../../components/ZButton.vue'

export default {
  components: {
    ZButton
  },
  data() {
    return {
      formData: {
        content: '',
        images: []
      },
      imageList: [],
      selectedTags: [],
      submitting: false,
    }
  },
  methods: {
        chooseImage() {
      const remainingCount = 9 - this.imageList.length
      if (remainingCount <= 0) {
        uni.showToast({
          title: '最多只能上传9张图片',
          icon: 'none'
        })
        return
      }
      
      uni.chooseImage({
        count: 1, // 每次选择1张
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
        sourceType: ['album'], // 从相册选择
        success: (res) => {
          uni.showLoading({
            title: '上传中...'
          })
          
          uni.uploadFile({
            url: this.$api.uploadImage, // 上传接口地址
            filePath: res.tempFilePaths[0],
            name: 'file',
            success: (uploadFileRes) => {
              try {
                let data = JSON.parse(uploadFileRes.data)
                this.imageList.push(data.data.url)
                uni.showToast({
                  title: '上传成功',
                  icon: 'success'
                })
              } catch (e) {
                console.error('解析上传结果失败:', e)
                uni.showToast({
                  title: '上传失败',
                  icon: 'none'
                })
              }
            },
            fail: (err) => {
              console.error('上传失败:', err)
              uni.showToast({
                title: '上传失败',
                icon: 'none'
              })
            },
            complete: () => {
              uni.hideLoading()
            }
          })
        },
        fail: (err) => {
          console.error('选择图片失败:', err)
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          })
        }
      })
    },

    deleteImage(index) {
      this.imageList.splice(index, 1)
    },

    toggleTag(tagId) {
      const index = this.selectedTags.indexOf(tagId)
      if (index > -1) {
        this.selectedTags.splice(index, 1)
      } else {
        if (this.selectedTags.length < 3) {
          this.selectedTags.push(tagId)
        } else {
          uni.showToast({
            title: '最多只能选择3个标签',
            icon: 'none'
          })
        }
      }
    },

    

    validateForm() {
      if (!this.formData.content.trim()) {
        uni.showToast({
          title: '请输入动态内容',
          icon: 'none'
        })
        return false
      }

      if (this.formData.content.length > 1000) {
        uni.showToast({
          title: '内容不能超过1000字',
          icon: 'none'
        })
        return false
      }

      return true
    },

        async submitPost() {
      if (!this.validateForm()) {
        return
      }
      
      this.submitting = true
      
      try {
        const submitData = {
          content: this.formData.content.trim(),
          images: this.imageList.join(','), // 直接使用已上传的图片URL数组
          user_id: this.userInfo.id
        }
        
        await this.$api.createUserPost(submitData)
        
        uni.showToast({
          title: '发布成功',
          icon: 'success'
        })
        
        // 延迟跳转，让用户看到成功提示
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        
      } catch (error) {
        console.error('发布失败:', error)
        uni.showToast({
          title: error.message || '发布失败',
          icon: 'none'
        })
      } finally {
        this.submitting = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.publish-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 40rpx 30rpx;
  padding-bottom: 140rpx; /* 为底部按钮留出空间 */
}

.title {
  text-align: center;
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 40rpx;
}

.content-card {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  margin-bottom: 30rpx;
}

.content-input {
  width: 100%;
  min-height: 300rpx;
  font-size: 32rpx;
  color: #333;
  line-height: 1.6;
  border: none;
  outline: none;
  resize: none;

  &::placeholder {
    color: #999;
  }
}

.divider {
  height: 2rpx;
  background-color: #f0f0f0;
  margin: 30rpx 0;
}

.bottom-section {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.image-item {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  
  .uploaded-image {
    width: 100%;
    height: 100%;
    border-radius: 15rpx;
  }
  
  .delete-btn {
    position: absolute;
    top: -10rpx;
    right: -10rpx;
    width: 40rpx;
    height: 40rpx;
    background-color: rgba(0, 0, 0, 0.6);
    color: #fff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24rpx;
    font-weight: bold;
  }
}

.image-upload {
  .upload-box {
    width: 200rpx;
    height: 200rpx;
    border: 2rpx solid #ddd;
    border-radius: 15rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fafafa;
    
    .plus-icon {
      font-size: 60rpx;
      color: #ffd700;
      font-weight: bold;
    }
  }
}

.image-counter {
  font-size: 28rpx;
  color: #999;
}

.tags-section {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  margin-bottom: 40rpx;
}

.tags-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 30rpx;
}

.tags-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.tag-item {
  padding: 15rpx 25rpx;
  background-color: #f0f0f0;
  border-radius: 25rpx;
  font-size: 28rpx;
  color: #666;
  transition: all 0.3s ease;

  &.selected {
    background-color: #ffd700;
    color: #333;
  }
}

.publish-btn-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #f0f0f0;
  z-index: 999;
}

.publish-btn {
  width: 100%;
  height: 88rpx;
  background-color: #666;
  color: #fff;
  border: none;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: 500;
  
  &:disabled {
    background-color: #ccc;
  }
}
</style>
